//Given an integer array of size n, find all elements that appear more than ⌊ n/
//3 ⌋ times. 
//
// Follow-up: Could you solve the problem in linear time and in O(1) space? 
//
// 
// Example 1: 
//
// 
//Input: nums = [3,2,3]
//Output: [3]
// 
//
// Example 2: 
//
// 
//Input: nums = [1]
//Output: [1]
// 
//
// Example 3: 
//
// 
//Input: nums = [1,2]
//Output: [1,2]
// 
//
// 
// Constraints: 
//
// 
// 1 <= nums.length <= 5 * 104 
// -109 <= nums[i] <= 109 
// 
// Related Topics Array Hash Table Sorting Counting 
// 👍 3362 👎 239


package leetcode.editor.en;

import java.util.ArrayList;
import java.util.List;

public class _229_MajorityElementIi {
    public static void main(String[] args) {
        Solution solution = new _229_MajorityElementIi().new Solution();
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public List<Integer> majorityElement(int[] nums) {
            int count1 = 0, count2 = 0;
            int r1 =0,r2 = 0;
            for (int i = 0; i < nums.length; i++) {
                if (count1>0 && nums[i]==r1){
                    count1++;
                }else if (count2>0&&nums[i]==r2){
                    count2++;
                }else if (count1==0){
                    count1 = 1;
                    r1 = nums[i];
                }else if (count2 == 0){
                    count2 = 1;
                    r2 = nums[i];
                }else {
                    count1--;
                    count2--;
                }
            }
            count1 = 0;
            count2 = 0;
            for (int num : nums) {
                if (num == r1) {
                    count1++;
                }else if (num == r2) {
                    count2++;
                }
            }
            List<Integer> r = new ArrayList<>();
            if (count1>(nums.length/3)){
                r.add(r1);
            }
            if (count2>(nums.length/3)){
                r.add(r2);
            }
            return r;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}